# apps/users/serializers.py
from rest_framework import serializers
from django.contrib.auth import get_user_model

from apps.menus.models import Menu
from apps.users.models import QBUser

User = get_user_model()

class UserSimpleSerializer(serializers.ModelSerializer):
    """
    简化版用户序列化器，用于外键引用（如试卷创建人等场景）
    """
    class Meta:
        model = User
        fields = ['id', 'username', 'full_name', 'role']
        # 只读，避免在创建时误修改用户
        read_only_fields = ['id', 'username', 'full_name', 'role']


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'full_name', 'email', 'role', 'is_active', 'date_joined']
        read_only_fields = ['id', 'date_joined']

class UserCreateSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['username', 'full_name', 'email', 'password','tenant']

    def create(self, validated_data):
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)  # 安全加密密码
        user.save()
        return user

class CurrentUserSerializer(serializers.ModelSerializer):
    menu = serializers.SerializerMethodField()
    real_name = serializers.CharField(source='full_name')
    permissions = serializers.SerializerMethodField()  # 新增字段

    class Meta:
        model = QBUser
        fields = ['id', 'username', 'real_name', 'role', 'email', 'is_staff', 'menu', 'permissions', 'tenant']

    def get_menu(self, obj):
        # 调用菜单视图获取用户菜单
        from apps.menus.views import MenuViewSet
        request = self.context.get('request')
        view = MenuViewSet()
        view.request = request
        view.format_kwarg = None
        return MenuViewSet().user_menu(request).data

    def get_permissions(self, obj):
        # 获取用户所有菜单的 name 字段作为权限码
        menus = Menu.objects.filter(roles=obj, is_active=True)
        return [menu.name for menu in menus]
